package calin.podcast;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import calin.podcast.MusicUtils.ServiceToken;

public class CalinPodcastList extends ListActivity 
implements ServiceConnection{
	// private CalinPodcastDbAdapter mDbHelper;
	private int mSort = 0;
	private List<String> playList = new ArrayList<String>();
	private File podcastDirectory;
	private String pathKey = "path";
    private ServiceToken mToken;

	// static {
	// System.loadLibrary("calin-jni");
	// System.loadLibrary("calin-test");
	// }
	//
	// public native String stringFromJNI();
	//
	// public native String stringPassJNI(String test);

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Restore preferences
		InputStream inputStream = null;
		try {
			// Log.d("Calin Podcast", " stringFromJNI: " + stringFromJNI());
			// Log.d("Calin Podcast", " stringPassJNI: " +
			// stringPassJNI("Show this"));
			podcastDirectory = ((Podcasts) this.getApplication())
					.getPodcastDirectory(CalinPodcastList.this);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		try {
			fillData();
			registerForContextMenu(getListView());
			setContentView(R.layout.podcasts_list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void fillData() {
		// Get all of the rows from the database and create the item list
		// Cursor podcastsCursor = mDbHelper.fetchAllPodcasts();
		// startManagingCursor(podcastsCursor);
		//
		// // Create an array to specify the fields we want to display in the
		// list
		// // (only TITLE)
		// String[] from = new String[] { CalinPodcastDbAdapter.KEY_TITLE };
		//
		// // and an array of the fields we want to bind those fields to (in
		// this
		// // case just text1)
		// int[] to = new int[] { R.id.title };

		// Now create a simple cursor adapter and set it to display
		// SimpleCursorAdapter podcasts = new SimpleCursorAdapter(this,
		// R.layout.podcasts_row, podcastsCursor, from, to);
		// String[] test;
		List<String> item = new ArrayList<String>();

		try {
			// test = ((Podcasts)
			// this.getApplication()).listFiles(podcastDirectory.getAbsolutePath());
			// Log.d("Calin Podcast", "String length is: " + test.length);
			// for (int i = 0; i < test.length; i++) {
			// Log.d("Calin Podcast", "String is: " + test[i]);
			// }
			Bundle bundle = getIntent().getExtras();

			File path = null;

			try {
				if (!bundle.isEmpty() && bundle.containsKey(pathKey))
					path = new File(bundle.getString(pathKey));
			} catch (Exception e) {

			}
			// Log.d("Calin Podcast", "Path is: " + path);
			if (path == null || !path.isDirectory())
				path = podcastDirectory;

			FilenameFilter filefilter = null;
			File[] files = null;
			filefilter = new FilenameFilter() {

				public boolean accept(File dir, String name) {
					File fileItem = new File(dir.getAbsolutePath() + "/" + name);

					if (fileItem.isDirectory())
						return true;

					return false;
				}
			};

			files = path.listFiles(filefilter);
			for (int i = 0; i < files.length; i++) {
				File file = files[i];

				item.add(file.getName() + "(" + file.listFiles().length + ")");
				playList.add(i, file.getPath());
			}
			filefilter = new FilenameFilter() {

				public boolean accept(File dir, String name) {
					File fileItem = new File(dir.getAbsolutePath() + "/" + name);

					if (fileItem.isDirectory())
						return false;

					return true;
				}
			};
			files = path.listFiles(filefilter);
			for (int i = 0; i < files.length; i++) {
				File file = files[i];

				item.add(file.getName());
				playList.add(i, file.getPath());
			}
			ArrayAdapter<String> podcasts = new ArrayAdapter<String>(this,
					R.layout.podcasts_row, item);
			setListAdapter(podcasts);
	        
	        mToken = MusicUtils.bindToService(this, this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		mSort = (int) id;
		File listItem = new File(playList.get(mSort));
		if (listItem.isFile()){
//			((Podcasts) this.getApplication()).play(listItem);
//			MusicUtils.playAll(this, playList, mSort, false);
//			try {
//			Uri uri = Uri.parse(playList.get(mSort));
//			String f_id = uri.getLastPathSegment();
//			long [] list = new long[] { Long.valueOf(f_id) };
//            MusicUtils.playAll(this, list, 0);
//            } catch (Exception e) {
//    			e.printStackTrace();
//    		}
			Intent intent = new Intent(CalinPodcastList.this,
					CalinPodcastMediaPlayer.class);
			intent.setData(Uri.parse(playList.get(mSort)));
			startActivityForResult(intent,Podcasts.ACTIVITY_SETTINGS_BROWSER);
		}else {
			Intent intent = new Intent(this, CalinPodcastList.class);
			Bundle bundle = new Bundle();
			bundle.putString(pathKey, playList.get((int) id));

			intent.putExtras(bundle);
			startActivityForResult(intent,Podcasts.ACTIVITY_SETTINGS_BROWSER);
			finish();
		}

		// Cursor podcast = mDbHelper.fetchPodcast(id);
		// String url = podcast.getString(podcast
		// .getColumnIndexOrThrow(CalinPodcastDbAdapter.KEY_URL));
		// Log.d("Calin Podcast",
		// "id: "
		// + podcast.getString(podcast
		// .getColumnIndexOrThrow(CalinPodcastDbAdapter.KEY_ROWID))
		// + "  title: "
		// + podcast.getString(podcast
		// .getColumnIndexOrThrow(CalinPodcastDbAdapter.KEY_TITLE))
		// + "  url: "
		// + podcast.getString(podcast
		// .getColumnIndexOrThrow(CalinPodcastDbAdapter.KEY_URL)));
		// try {
		// List<String> item = new ArrayList<String>();
		// File[] files = podcastDirectory.listFiles();
		// String path=playList.get(mSort);
		// for (int i = 0; i < files.length; i++) {
		// File file = files[i];
		//
		// item.add(file.getPath());
		// if (id == i) {
		// path = file.getPath();
		// }
		// }
		//
		// if(path=="") return;
		//
		// if (mPlayer != null) {
		// mPlayer.release();
		// mPlayer = null;
		// }
		// mPlayer = new MediaPlayer();
		// mPlayer.setDataSource(path);
		// mPlayer.setOnCompletionListener(new
		// MediaPlayer.OnCompletionListener() {
		// @Override
		// public void onCompletion(MediaPlayer mp) {
		// mp.stop();
		// mp.release();
		// mSort++;
		// String path=playList.get(mSort);
		// }
		// });
		// mPlayer.prepare();
		// mPlayer.start();
		// } catch (IOException e) {
		// Log.d("Calin Podcast", " IOException error: " + e.toString());
		// } catch (IllegalArgumentException e) {
		// Log.d("Calin Podcast",
		// " IllegalArgumentException error: " + e.toString());
		// }
		// Intent i = new Intent(this, NoteEdit.class);
		// i.putExtra(NotesDbAdapter.KEY_ROWID, id);
		// startActivityForResult(i, ACTIVITY_EDIT);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			menu.add(0, Podcasts.CONFIG_ID, 0, R.string.menu_settings);
			menu.add(0, Podcasts.ABOUTUS_ID, 1, R.string.menu_about_us);
			super.onCreateOptionsMenu(menu);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case Podcasts.CONFIG_ID:
			settingsPodcast();
			return true;
		case Podcasts.ABOUTUS_ID:
			aboutUsPodcast();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void settingsPodcast() {
		try {
			Intent i = new Intent(this, CalinPodcastSettings.class);
			startActivityForResult(i, Podcasts.ACTIVITY_SETTINGS);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void aboutUsPodcast() {
		try {
			Intent i = new Intent(this, CalinPodcastAboutUs.class);
			startActivityForResult(i, Podcasts.ACTIVITY_ABOUTUS);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		// if (mPlayer != null) {
		// mPlayer.release();
		// mPlayer = null;
		// }
		// super.onBackPressed();
		Log.d("Calin Podcast", "onBackPressed: Yes");
		try {
			Intent intent = new Intent(this, CalinPodcast.class);
			startActivity(intent);
			finish();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
    /*
     * This listener gets called when the media scanner starts up or finishes, and
     * when the sd card is unmounted.
     */
    private BroadcastReceiver mScanListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action) ||
                    Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)) {
                MusicUtils.setSpinnerState(CalinPodcastList.this);
            }
            mReScanHandler.sendEmptyMessage(0);
        }
    };

    private BroadcastReceiver mNowPlayingListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MediaPlaybackService.META_CHANGED)) {
                getListView().invalidateViews();
            } else if (intent.getAction().equals(MediaPlaybackService.QUEUE_CHANGED)) {
//                if (mDeletedOneRow) {
//                    // This is the notification for a single row that was
//                    // deleted previously, which is already reflected in
//                    // the UI.
//                    mDeletedOneRow = false;
//                    return;
//                }
//                // The service could disappear while the broadcast was in flight,
//                // so check to see if it's still valid
//                if (MusicUtils.sService == null) {
//                    finish();
//                    return;
//                }
//                Cursor c = new NowPlayingCursor(MusicUtils.sService, mCursorCols);
//                if (c.getCount() == 0) {
//                    finish();
//                    return;
//                }
//                mAdapter.changeCursor(c);
            }
        }
    };
    
    private BroadcastReceiver mTrackListListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            getListView().invalidateViews();
//            if (!mEditMode) {
//                MusicUtils.updateNowPlaying(CalinPodcastList.this);
//            }
        }
    };
    
    private Handler mReScanHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            if (mAdapter != null) {
//                getTrackCursor(mAdapter.getQueryHandler(), null, true);
//            }
            // if the query results in a null cursor, onQueryComplete() will
            // call init(), which will post a delayed message to this handler
            // in order to try again.
        }
    };

    public void onServiceConnected(ComponentName name, IBinder service)
    {
        IntentFilter f = new IntentFilter();
        f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
        f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
        f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        f.addDataScheme("file");
        registerReceiver(mScanListener, f);

//        if (mAdapter == null) {
//            //Log.i("@@@", "starting query");
//            mAdapter = new TrackListAdapter(
//                    getApplication(), // need to use application context to avoid leaks
//                    this,
//                    mEditMode ? R.layout.edit_track_list_item : R.layout.track_list_item,
//                    null, // cursor
//                    new String[] {},
//                    new int[] {},
//                    "nowplaying".equals(mPlaylist),
//                    mPlaylist != null &&
//                    !(mPlaylist.equals("podcasts") || mPlaylist.equals("recentlyadded")));
//            setListAdapter(mAdapter);
//            setTitle(R.string.working_songs);
//            getTrackCursor(mAdapter.getQueryHandler(), null, true);
//        } else {
//            mTrackCursor = mAdapter.getCursor();
//            // If mTrackCursor is null, this can be because it doesn't have
//            // a cursor yet (because the initial query that sets its cursor
//            // is still in progress), or because the query failed.
//            // In order to not flash the error dialog at the user for the
//            // first case, simply retry the query when the cursor is null.
//            // Worst case, we end up doing the same query twice.
//            if (mTrackCursor != null) {
//                init(mTrackCursor, false);
//            } else {
//                setTitle(R.string.working_songs);
//                getTrackCursor(mAdapter.getQueryHandler(), null, true);
//            }
//        }
//        if (!mEditMode) {
//            MusicUtils.updateNowPlaying(this);
//        }
    }
    
    public void onServiceDisconnected(ComponentName name) {
        // we can't really function without the service, so don't
        finish();
    }

	// public void onDestroy() {
	// if (mPlayer != null) {
	// mPlayer.release();
	// mPlayer = null;
	// }
	//
	// ((Podcasts) this.getApplication()).closeDatabase();
	// super.onDestroy();
	// }
}